import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:orginone/components/XDialogs/dialog_utils.dart';
import 'package:orginone/components/XTextField/XTextField.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/extension/index.dart';
import 'package:orginone/components/Tip/ToastUtils.dart';
import 'package:orginone/components/ProcessDetailsWidget/components/WorkTool.dart';
import 'package:orginone/config/theme/space.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:orginone/dart/core/work/task.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/utils/log/log_util.dart';

import '../../../pages/portal/assets_management/assets_module/asset_select_modal.dart';
import '../../XDialogs/LoadingDialog.dart';
import 'WorkNetWork.dart';

// ignore: must_be_immutable
class BottomActionWidget extends StatelessWidget {
  final IWorkTask? todo;
  BottomActionWidget(
      {super.key, required this.todo, required this.comment});

  final TextEditingController? comment;
  List<XWorkTask>? newWorkTask = [];
  List<String> startArry = [];

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: expensiveOperation(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return _buildMainView(context);
        }
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
    );
  }

  // 耗时操作
  Future<String> expensiveOperation() async {
    startArry.clear();
    newWorkTask?.clear();
    for(XWorkTask xWorkTask in todo!.instance!.tasks!) {
      if (xWorkTask.approveType == "起始") {
        if (startArry.isEmpty || !startArry.contains("起始")) {
          startArry.add(xWorkTask.approveType!);
          newWorkTask?.add(xWorkTask);
        }
      } else {
        newWorkTask?.add(xWorkTask);
      }
    }
    return '完成';
  }

  _buildMainView(BuildContext context) {
    return <Widget>[
      // _opinion(),
      _approval(context)
    ].toColumn();
  }

  ///审批
  Widget _approval(BuildContext context) {
    if (todo?.metadata.status != 1) {
      return Container();
    }
    return Container(
      width: double.infinity,
      height: 80.h,
      decoration: BoxDecoration(
          color: XColors.backgroundColor,
          border:
              Border(top: BorderSide(color: Colors.grey.shade300, width: 0.5))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          // _button(
          //     text: '驳回',
          //     textColor: Colors.white,
          //     color: Colors.red,
          //     onTap: () {
          //       XLogUtil.d('驳回');
          //       approval(context, TaskStatus.refuseStart.status,
          //           comment: comment?.text);
          //     }),
          (todo?.taskdata.approveType == '起始' && todo!.taskdata!.title!.contains('驳回')) ? _button(
          text: '撤回',
          textColor: Colors.white,
          color: XColors.themeColor,
          onTap: () {
            XLogUtil.d('撤回');
            todo!.recallApply();
            Navigator.pop(context);
          }) : (todo?.taskdata.approveType != AddNodeType.CC && todo?.taskdata.approveType != AddNodeType.END) ? _button(
              text: '退回',
              textColor: Colors.white,
              color: Colors.red,
              onTap: () {
                XLogUtil.d('退回');
                PickerUtils.showWorktaskPicker(context,
                  tasks: newWorkTask!.where((element) => element.status == 100 || element.approveType == '起始')
                      .toList(),
                  workcallback: (int index, XWorkTask worktask) {
                    LoadingDialog.showLoading(context, msg: "加载中...");
                    approval(context, TaskStatus.backStartStatus.status,
                        comment: comment?.text, backId: "起始" == worktask.approveType ? "1" : worktask.id, isSkip: false);
                  },);
              }): Container(),
          (todo?.taskdata.approveType == '起始' && todo!.taskdata!.title!.contains('驳回')) ? _button(
              text: '提交',
              textColor: Colors.white,
              color: XColors.themeColor,
              onTap: () {
                XLogUtil.d('提交');
                ToastUtils.showMsg(msg: '重新提交请前往PC端进行操作');
              }).paddingHorizontal(AppSpace.page) : _button(
              text: '同意',
              textColor: Colors.white,
              color: XColors.themeColor,
              onTap: () {
                // LogUtil.d('审批');
                LoadingDialog.showLoading(context, msg: "加载中...");
                approval(context, TaskStatus.approvalStart.status,
                    comment: comment?.text);

                // Get.toNamed(Routers.approveOpinion,
                //     arguments: {'todo': todo, 'comment': comment});
              }).paddingHorizontal(AppSpace.page),
        ],
      ),
    );
  }

  Widget _opinion() {
    if (todo?.metadata.status != 1) {
      return Container();
    }
    return XTextField.input(
      title: "备注",
      showLine: true,
      controller: comment,
      hint: "请填写备注信息",
      maxLines: 4,
    ).paddingTop(AppSpace.listItem);
  }

  Widget _button(
      {VoidCallback? onTap,
      required String text,
      Color? textColor,
      Color? color,
      BoxBorder? border}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        alignment: Alignment.center,
        height: AppSpace.sectionH,
        width: (Get.width - AppSpace.page * 3) / 2,
        decoration: BoxDecoration(
          color: color,
          borderRadius: BorderRadius.circular(4.w),
          border: border,
        ),
        child: Text(
          text,
          style: TextStyle(color: textColor, fontSize: 24.sp),
        ),
      ),
    );
  }

  //网络请求
  void approval(BuildContext context, int status, {String? comment, String? backId, bool? isSkip}) async {
    // if (comment == null || comment.isEmpty) {
    //   return ToastUtils.showMsg(msg: '请输入审批意见');
    // }
    var node = WorkTool.getNodeByNodeId(todo?.taskdata.nodeId ?? "",
        node: todo?.instanceData?.node);
    if (null != node &&
        node.other is Map<String, dynamic> &&
        node.other?['executors'] != null &&
        node.other?['executors'] is List &&
        (node.other?['executors'] as List).isNotEmpty) {
      XLogUtil.dd("有任务办事审批");
      ToastUtils.showMsg(msg: "暂不支持有执行器的办事审批，请先在PC端上审批!");
      LoadingDialog.dismiss(context);
    } else {
      await WorkNetWork.approvalTask(
          status: status,
          comment: comment,
          todo: todo!,
          backId: backId,
          isSkip: isSkip,
          onSuccess: () {
            LoadingDialog.dismiss(context);
            RoutePages.back(context);
          });
    }
  }
}
